package com.justgame.project.service.system.controller.form.custom;

import com.justgame.project.cloud.common.util.WeChatUtils;
import com.justgame.project.service.system.service.ISysUserInfoService;
import com.justgame.project.service.system.vo.UserAuthorizationResult;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.util.Assert;
import rx.functions.Func1;
import rx.functions.Func2;

@Setter
@ApiModel("登录提交表单")
public class LoginPostForm{

    @ApiModelProperty("用户名")
    private String userName;

    @ApiModelProperty("密码")
    private String password;

    @ApiModelProperty("邮箱")
    private String eMail;

    @ApiModelProperty("邮箱验证码")
    private String eMailCode;

    @ApiModelProperty("手机号")
    private String phoneNumber;

    @ApiModelProperty("短信验证码")
    private String smsCode;

    @ApiModelProperty("授权Code")
    private String jsCode;

    @Getter
    @ApiModelProperty("登录方式")
    private LoginType loginType = LoginType.PASSWORD;

    @Getter
    @RequiredArgsConstructor
    public enum LoginType{
        PASSWORD(
                (form)->{
                Assert.hasLength(form.userName,"必须提供账号");
                Assert.hasLength(form.password,"必须提供密码");
                return true;
        },(service,form)->service.loginByUserNameAndPassword(form.userName,form.password)),
        EMAIL(
                (form)->{
                Assert.hasLength(form.eMail,"必须提供邮箱");
                Assert.hasLength(form.eMailCode,"必须提供邮证码");
                return true;
        },(service,form)->service.loginByEmail(form.eMail,form.eMailCode)),
        PHONE(
                (form)->{
                Assert.hasLength(form.phoneNumber,"必须提供手机号");
                Assert.hasLength(form.smsCode,"必须提供验证码");
                 return true;
        },(service,form)->service.loginByPhoneNumber(form.phoneNumber,form.smsCode)),
        WX(
                (form)->{
                    Assert.hasLength(form.jsCode,"登陆失效");
                    return true;
                },
                (service,form)->service.loginByWx(WeChatUtils.getWeChatAuthResult(form.jsCode))
        );
        /**
         * 表单校验方法
         */
        final Func1<LoginPostForm,Boolean> checkMethod;
        /**
         * 不同登录方式执行的登录方法
         */
        final Func2<ISysUserInfoService,LoginPostForm, UserAuthorizationResult> loginHandle;
    }

    /**
     * 判空校验
     */
    private void loginTypeCheck(){
        Assert.notNull(loginType,"未知的登录方式");
        Assert.isTrue(loginType.checkMethod.call(this),"登录校验失败");
    }

    /**
     * 入参表单校验
     */
    public void paramsCheck(){
        loginTypeCheck();
    }
}
